import axios from 'axios'
import router from '@/router/router.js'
import { ElNotification } from 'element-plus'

const baseURL = 'http://localhost:9999' // URL地址

const instance = axios.create({
  baseURL, // URL地址
  timeout: 300 * 1000 // 超时时间（单位：毫秒）
})

// 【请求拦截器】
instance.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    // ElNotification({
    //   type: 'error',
    //   title: '提示',
    //   message: '请稍后重试',
    //   duration: 3000,
    //   offset: 80,
    //   position: 'top-right',
    //   dangerouslyUseHTMLString: true
    // });
    Promise.reject(err);
  }
)

// 【响应拦截器】
instance.interceptors.response.use(
  (res) => {
    if (String(res.data.code) === '200') {
      return res;
    } else {
      return ElNotification({
        type: 'error',
        title: '提示',
        message: res.data.msg,
        duration: 2000,
        offset: 80,
        position: 'top-right',
        dangerouslyUseHTMLString: true
      });
    }
  },
  (err) => {
    if (err.response?.status === 401 || err.response?.status === 1) {
      router.push('/err');
    }
    ElNotification({
      type: 'error',
      title: '提示',
      message: '请稍后重试',
      duration: 3000,
      offset: 80,
      position: 'top-right',
      dangerouslyUseHTMLString: true
    });
    Promise.reject(err);
  }
)

export default instance;
export { baseURL };
